
import 'dart:ffi';


import 'package:asperm/tools/widget_extension.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

import '../generated/l10n.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../tools/auth.dart';
import '../tools/const.dart';
import '../tools/data_base_helper.dart';
import '../tools/divider_input_formatter.dart';
import '../tools/tools.dart';
import '../tools/user_repository.dart';
import '../views/common_button.dart';
import '../views/myDialog.dart';

enum ProcessStep {
  inputNickname,  // 输入昵称
  inputAnswer,    // 输入答案
  success      // 得到结果
}
class ForgetPasswordPage extends StatefulWidget {
  ForgetPasswordPage({Key? key}) : super(key: key);

  @override
  State<ForgetPasswordPage> createState() => _ForgetPasswordPageState();
}

class _ForgetPasswordPageState extends State<ForgetPasswordPage> {


  final firstController = TextEditingController();
  final secondController = TextEditingController.fromValue(
      TextEditingValue());
  final thirdController = TextEditingController.fromValue(
      TextEditingValue());
  String firstValue = '';

  String secondValue = '';
  String thirdValue = '';

  bool isButtonEnabled = true;
  bool isAgreementSelected = false;
  bool isEmailLogin = false;

  String questionValue = '';
  String securityAnswer = '';
  String password = '';


  final FocusNode focusNode_nickName = FocusNode();
  final FocusNode focusNode_password = FocusNode();

  int inputLength = 0;
  bool isVisitor = false;
  ProcessStep currentStep = ProcessStep.inputNickname;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    thirdController.text = '123';
  }

  @override
  void dispose() {
    super.dispose();
    //释放
    focusNode_nickName.dispose();
    focusNode_password.dispose();

  }


  @override
  Widget build(BuildContext context) {
    // 获取屏幕大小
    return Scaffold(
      body: GestureDetector(
          onTap: () {
            // 调用这个方法会隐藏软键盘
            FocusScope.of(context).unfocus();
          },
          child: SingleChildScrollView(
            child: Container(
              height: screenHeight(context),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      buildSmallLogo(context),
                      firstWidget(context),
                      secondWidget(context),
                      thirdWidget(context),
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.only(bottom: 40.h),
                    child: Column(
                      children: [
                        buildLoginBtn(context),
                        buildLoginGuestBtn(context),
                      ],
                    ),
                  )
                ],
              ),
            ),
          )),
    );
  }



  //small logo
  Widget buildSmallLogo(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: 78.h, left: 20.w),
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            'Retrieve Password',
            style: TextStyle(
              color: Color(0xff5A5A5A),
              fontSize: 30.sp,
              fontWeight: FontWeight.w700,
            ),
            textAlign: TextAlign.center,
            maxLines: 1, // 限制文本显示的最大行数为2
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }
  Widget firstWidget(BuildContext context) {
    String title = 'Username';
    if(currentStep == ProcessStep.inputNickname){
      title = 'Username';
    }else{
      title = 'Security Question';
    }

    return Container(
      child: Column(
        children: [
          Container(
            // color: Colors.red,
            margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 0.w),
            child: Container(
              alignment: Alignment.centerLeft,
              child: Text(
                title,
                style: TextStyle(
                  color: isVisitor ? Color(0xffED6D20) : Color(0xff5A5A5A),
                  fontSize: 16.sp,
                  fontWeight: isVisitor ? FontWeight.w600 : FontWeight.w400,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              left: 20.w,
              right: 20.w,
              top: 20.h,
            ),
            height: 48.h,
            decoration: BoxDecoration(
              border: Border.all(
                color: Color(0xffDADADA), // 下划线颜色
                width: 1.h, //
              ),
              borderRadius: BorderRadius.circular(4.h),
            ),
            child: Row(
              children: [
                // Email输入TextField
                SizedBox(
                  width: 20.w,
                ),
                Expanded(
                  child: TextField(
                    readOnly: currentStep != ProcessStep.inputNickname,
                    focusNode: focusNode_nickName,
                    // autofocus: isEmailLogin,
                    controller: firstController,
                    maxLines: 1,
                    inputFormatters: [
                      // 限制输入长度为 20
                      LengthLimitingTextInputFormatter(20),
                      // 过滤输入，只允许字母、数字、汉字和部分常见字符，不允许空格
                      FilteringTextInputFormatter.allow(RegExp(r'[^\s]')),
                    ],
                    onChanged: (value) {
                      setState(() {
                        firstValue = value;

                      });
                    },
                    decoration: InputDecoration(
                      border: OutlineInputBorder(borderSide: BorderSide.none),
                      // enabledBorder: UnderlineInputBorder(
                      //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 下划线颜色
                      // ),
                      // focusedBorder: UnderlineInputBorder(
                      //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 获得焦点时下划线颜色
                      // ),
                      // labelText: S.of(context).Email,
                      hintText: S.of(context).EnterNickname,
                      hintStyle: TextStyle(
                        fontSize: 16.sp,
                        color: Color(0xff888888),
                        fontWeight: FontWeight.w400,
                      ),
                      contentPadding: EdgeInsets.symmetric(
                          vertical: 0, horizontal: 0), // 调整文字位置以垂直居中
                    ),
                    keyboardType: TextInputType.text,
                    cursorColor: Color(0xFFffED6D20),
                    style: TextStyle(
                      fontSize: 16.sp,
                    ),
                  ),
                ),
                // 取消按钮，仅当有输入时显示
                Offstage(
                  offstage: firstValue.isEmpty || currentStep != ProcessStep.inputNickname,
                  child: IconButton(
                    alignment: Alignment.centerRight,
                    icon: Icon(
                      Icons.cancel,
                      color: Colors.grey,
                      size: 20.w,
                    ),
                    onPressed: () {
                      setState(() {
                        firstValue = '';
                        firstController.clear();
                      });
                    },
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget secondWidget(BuildContext context) {
    return Visibility(
      visible: currentStep != ProcessStep.inputNickname,
      child: Container(
        child: Column(
          children: [
            Container(
              // color: Colors.red,
              margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 0.w),
              child: Container(
                alignment: Alignment.centerLeft,
                child: Text(
                  'Security Answer',
                  style: TextStyle(
                    color: isVisitor ? Color(0xffED6D20) : Color(0xff5A5A5A),
                    fontSize: 16.sp,
                    fontWeight: isVisitor ? FontWeight.w600 : FontWeight.w400,
                  ),
                  textAlign: TextAlign.center,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.only(
                left: 20.w,
                right: 20.w,
                top: 20.h,
              ),
              height: 48.h,
              decoration: BoxDecoration(
                border: Border.all(
                  color: Color(0xffDADADA), // 下划线颜色
                  width: 1.h, //
                ),
                borderRadius: BorderRadius.circular(4.h),
              ),
              child: Row(
                children: [
                  // Email输入TextField
                  SizedBox(
                    width: 20.w,
                  ),
                  Expanded(
                    child: TextField(
                      focusNode: focusNode_password,
                      // autofocus: isEmailLogin,
                      controller: secondController,
                      maxLines: 1,
                      inputFormatters: [
                        // 限制输入长度为 20
                        LengthLimitingTextInputFormatter(20),
                        // 过滤输入，只允许字母、数字、汉字和部分常见字符，不允许空格
                        FilteringTextInputFormatter.allow(RegExp(r'[^\s]')),
                      ],
                      onChanged: (value) {
                        setState(() {
                          secondValue = value;

                        });
                      },
                      decoration: InputDecoration(
                        border: OutlineInputBorder(borderSide: BorderSide.none),
                        // enabledBorder: UnderlineInputBorder(
                        //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 下划线颜色
                        // ),
                        // focusedBorder: UnderlineInputBorder(
                        //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 获得焦点时下划线颜色
                        // ),
                        // labelText: S.of(context).Email,
                        hintText: 'Enter Answer',
                        hintStyle: TextStyle(
                          fontSize: 16.sp,
                          color: Color(0xff888888),
                          fontWeight: FontWeight.w400,
                        ),
                        contentPadding: EdgeInsets.symmetric(
                            vertical: 0, horizontal: 0), // 调整文字位置以垂直居中
                      ),
                      keyboardType: TextInputType.text,
                      cursorColor: Color(0xFFffED6D20),
                      style: TextStyle(
                        fontSize: 16.sp,
                      ),
                    ),
                  ),
                  // 取消按钮，仅当有输入时显示
                  Offstage(
                    offstage: secondValue.isEmpty,
                    child: IconButton(
                      alignment: Alignment.centerRight,
                      icon: Icon(
                        Icons.cancel,
                        color: Colors.grey,
                        size: 20.w,
                      ),
                      onPressed: () {
                        setState(() {
                          secondValue = '';
                          secondController.clear();
                        });
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget thirdWidget(BuildContext context) {
    return Visibility(
      visible: currentStep == ProcessStep.success,
      child: Container(
        child: Column(
          children: [
            Container(
              // color: Colors.red,
              margin: EdgeInsets.only(top: 20.h, left: 20.w, right: 0.w),
              child: Container(
                alignment: Alignment.centerLeft,
                child: Text(
                  'Password',
                  style: TextStyle(
                    color: isVisitor ? Color(0xffED6D20) : Color(0xff5A5A5A),
                    fontSize: 16.sp,
                    fontWeight: isVisitor ? FontWeight.w600 : FontWeight.w400,
                  ),
                  textAlign: TextAlign.center,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.only(
                left: 20.w,
                right: 20.w,
                top: 20.h,
              ),
              height: 48.h,
              decoration: BoxDecoration(
                border: Border.all(
                  color: Color(0xffDADADA), // 下划线颜色
                  width: 1.h, //
                ),
                borderRadius: BorderRadius.circular(4.h),
              ),
              child: Row(
                children: [
                  // Email输入TextField
                  SizedBox(
                    width: 20.w,
                  ),
                  Expanded(
                    child: TextField(
                      readOnly: true,
                      // autofocus: isEmailLogin,
                      controller: thirdController,
                      maxLines: 1,
                      inputFormatters: [
                        // 限制输入长度为 20
                        LengthLimitingTextInputFormatter(20),
                        // 过滤输入，只允许字母、数字、汉字和部分常见字符，不允许空格
                        FilteringTextInputFormatter.allow(RegExp(r'[^\s]')),
                      ],
                      decoration: InputDecoration(
                        border: OutlineInputBorder(borderSide: BorderSide.none),
                        // enabledBorder: UnderlineInputBorder(
                        //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 下划线颜色
                        // ),
                        // focusedBorder: UnderlineInputBorder(
                        //   borderSide: BorderSide(color: Color(0xFFD8D8D8)), // 获得焦点时下划线颜色
                        // ),
                        // labelText: S.of(context).Email,
                        hintText: 'Enter Answer',
                        hintStyle: TextStyle(
                          fontSize: 16.sp,
                          color: Color(0xff888888),
                          fontWeight: FontWeight.w400,
                        ),
                        contentPadding: EdgeInsets.symmetric(
                            vertical: 0, horizontal: 0), // 调整文字位置以垂直居中
                      ),
                      keyboardType: TextInputType.text,
                      cursorColor: Color(0xFFffED6D20),
                      style: TextStyle(
                        fontSize: 16.sp,
                      ),
                    ),
                  ),
                  // 取消按钮，仅当有输入时显示
                  Offstage(
                    offstage: thirdValue.isEmpty,
                    child: IconButton(
                      alignment: Alignment.centerRight,
                      icon: Icon(
                        Icons.cancel,
                        color: Colors.grey,
                        size: 20.w,
                      ),
                      onPressed: () {
                        setState(() {
                          thirdValue = '';
                          thirdController.clear();
                        });
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }


  //登录 事件
  loginAction() async {
    // 关闭键盘
    FocusScope.of(context).unfocus();
  }


  // 登录按钮
  Widget buildLoginBtn(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 20.h),
      // 左右各16像素的边距
      child: AspectRatio(
        aspectRatio: 335.w / 48.h, // 设置长宽比为343:50
        child: CommonButton(
          // title: S.of(context).Verification,
          title: currentStep == ProcessStep.inputNickname ? S.of(context).next :'RETRIEVE',
          isEnable: isButtonEnabled,
          borderRadius: 5.w,
          onTap: () async {

            loginAction();
            if(currentStep == ProcessStep.inputNickname){

              User? user = await UserRepository().getUserFromUsername(firstValue);
              if(user == null){
                showToast('User not found');
                return;
              }
              setState(() {
                questionValue = user.securityQuestion;
                securityAnswer = user.securityAnswer;
                password = user.password;

                currentStep = ProcessStep.inputAnswer;
                firstController.text = questionValue;
              });

            }else if(currentStep == ProcessStep.inputAnswer){
              if(secondValue != securityAnswer){
                showToast('Answer is incorrect');
                return;
              }
              setState(() {

                currentStep = ProcessStep.success;
                thirdController.text = password;
              });
            }


          },
        ),
      ),
    );
  }

  Widget buildLoginGuestBtn(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 20.h),
      // 左右各16像素的边距
      child: AspectRatio(
        aspectRatio: 335.w / 48.h, // 设置长宽比为343:50
        child: CommonButton(
          // title: S.of(context).Verification,
          bgColor: Colors.transparent,
          title: 'Back',
          textColor: globalColor(),
          borderRadius: 5.w,
          onTap: () {

            loginAction();
            Navigator.pop(context);

          },
        ),
      ),
    );
  }

}
